import { createRouter, createWebHashHistory } from "vue-router";
import Home from "../components/Home.vue";
import storage from "../utils/storage";
import api from "../api";
import utils from "../utils/utils";
import { storeToRefs } from "pinia";
import { useUserInfoStore } from "../store/useStore.js";
import { ElMessage, ElMessageBox } from "element-plus";

const routes = [
  {
    path: "/",
    name: "Home",
    component: Home,
    redirect: "/welcome",
    meta: {
      title: "首页",
    },
    // 子路由：当需要在当前页面通过路由跳转，切换页面中一部分页面时使用子路由，在父页面中使用router-view动态展示
    children: [
      {
        name: "Welcome",
        path: "welcome",
        meta: {
          title: "欢迎",
        },
        component: () => import("../views/Welcome.vue"),
      },
      {
        name: "Menu",
        path: "/system/menu",
        meta: {
          title: "菜单管理",
        },
        component: () => import("../views/system/Menu.vue"),
      },
      {
        name: "Role",
        path: "/system/role",
        meta: {
          title: "角色管理",
        },
        component: () => import("../views/system/Role.vue"),
      },
      {
        name: "User",
        path: "/system/user",
        meta: {
          title: "运营账号管理",
        },
        component: () => import("../views/system/User.vue"),
      },
      {
        name: "Seller",
        path: "/system/dealer",
        meta: {
          title: "经销商账号管理",
        },
        component: () => import("../views/system/Seller.vue"),
      },
      {
        name: "Dept",
        path: "/system/dept",
        meta: {
          title: "机构管理",
        },
        component: () => import("../views/system/Dept.vue"),
      },
      {
        name: "Category",
        path: "/system/category",
        meta: {
          title: "产品类别管理",
        },
        component: () => import("../views/system/Category.vue"),
      },
    ],
  },
  {
    name: "Login",
    path: "/login",
    // 可以添加权限
    meta: {
      title: "登录",
    },
    component: () => import("../views/Login.vue"),
  },
  {
    name: "404",
    path: "/404",
    // 可以添加权限
    meta: {
      title: "页面找不到",
    },
    component: () => import("../views/404.vue"),
  },
];

const router = createRouter({
  history: createWebHashHistory(),
  routes,
});

// 路由守卫
router.beforeEach((to, from, next) => {
  const { userInfo } = storeToRefs(useUserInfoStore());
  if (!userInfo.value.userName && to.name != "Login") {
    ElMessage({
      message: "亲你还没有登陆哦！请先登陆再访问哟✨✨✨",
      type: "warning",
    });
    router.push("/login");
    return;
  }
  if (router.hasRoute(to.name)) {
    // 有权限则将标签页title进行改变路由meta中的title--->并进入页面
    document.title = to.meta.title;
    next();
  } else {
    next("/404");
  }
});

export default router;
